import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import 'search_item.dart';

const List<String> filterName = ['QStar'];

class SearchView extends StatefulWidget {
  const SearchView({super.key});

  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> implements BLESearchTableViewDelegate {
  BLESearchTableView? _tableView;
  @override
  void initState() {
    super.initState();
    _tableView = BLESearchTableView(
        filterName: filterName,
        duration: 20000000,
        agreement: this,
        contentColor: Colors.white,
        bgViewForHeader: (child) => Container(color: Colors.transparent, child: child),
        bgViewForFooter: (child) => Container(color: Colors.transparent, child: child));
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // _tableView?.refreshKey?.currentState?.show();
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return _tableView!;
    });
  }

  @override
  List<RowModel> listModelForHeader(String appVersion) {
    return [];
  }

  @override
  List<RowModel> listModelForFooter(String appVersion) {
    return [];
  }

  @override
  List<RowModel> listModelForSection(List<String> list) {
    return [];
  }

  @override
  void methodForClickBLESearchTableView(BLESearchTableViewClickType type, String tag) {
    switch (type) {
      case BLESearchTableViewClickType.header:
        break;
      case BLESearchTableViewClickType.footer:
        break;
      case BLESearchTableViewClickType.section:
        break;
    }
  }

  @override
  Widget viewForRowInSection(DSPeripheral peripheral, int section, int row, bool isOn) {
    LogRecorder.addLog(
        '=====>.  搜索到的外设：${peripheral.name} : (${peripheral.peripheral?.result.device.advName}) : (${peripheral.peripheral?.mac ?? ''})');
    return SearchItem(
      peripheral: peripheral,
      onClick: () => _tableView?.clickDevice(section, row),
      onLongPress: () => _tableView?.changeDeviceName(section, row, peripheral.peripheral),
    );
  }

  ///修改设备名称
  void changeDeviceName() {
    for (var i = 0; i < (_tableView?.isonList ?? []).length; i++) {
      List<bool> list = _tableView!.isonList![i];
      for (var j = 0; j < list.length; i++) {
        bool isconnect = list[j];
        if (isconnect) {
          DSPeripheral peripheral = _tableView!.deviceList[i].values.first[j];
          _tableView?.changeDeviceName(i, j, peripheral.peripheral);
        }
      }
    }
  }
}
